#include<stdio.h> 
#include<string.h>
#include<unistd.h> 
#include<stdlib.h>
#include<sys/wait.h>
int main()
{
    //1.创建管道
    int pipefd[2] = {0};
    if(pipe(pipefd) <0)
    {
        perror("pipe error:");
        return 1;
    }
    //2.创建子进程 
    //3.关闭对应的读写端,创建单向信道->这里我们选择父进程读取,子进程写入
    //父进程关闭pipefd[1] 子进程关闭pipefd[0]
    if(fork() == 0)
    {
        //child
        close(pipefd[0]);//子进程关闭读端
        //子进程向管道中写入数据
        const char* msg = "hello Mango";
        while(1)
        {
            write(pipefd[1],msg,strlen(msg));
        }
        close(pipefd[1]);//子进程写入完毕,关闭写端
        exit(0);
    }
    //father
    close(pipefd[1]);//父进程关闭写端
    //父进程从管道读取数据
    while(1)
    {
        char buffer[64] = {0};//清空缓冲区
        ssize_t s = read(pipefd[0],buffer,sizeof(buffer)-1);
        if(s == 0){
            printf("writer quit!\n");
            break;
        }
        else if(s>0){
            buffer[s] = '\0';
            printf("child says to father:%s\n",buffer);
        }
        else{
            printf("read error\n");
            break;
        }
        //读取一条信息后休眠5s就退出
        printf("reading is leaving\n");
        sleep(5);
        break;
    }
    close(pipefd[0]);//父进程读取完成,关闭读端

    //获取子进程的退出信息
    int status = 0;
    waitpid(-1,&status,0);//需要引用#include<sys/wait.h>头文件
    printf("exit code:%d\n",(status>>8)&0xFF);
    printf("signal:%d\n",status&0x7F);
    
    return 0;
}